package ee.serge.client.content;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

import ee.serge.client.AlertBox;
import ee.serge.client.Move;
import ee.serge.service.Service;
import ee.serge.shared.ContentPopup;
import ee.serge.shared.Feedback;
import ee.serge.util.FormPanel;
import ee.serge.util.Headers;
import ee.serge.util.Loader;
import ee.serge.util.RatingPanel;
import ee.serge.util.SimpleCallback;
import ee.serge.util.bootstrap.BButton;
import ee.serge.util.bootstrap.BButtonBar;

public class AddReviewPopup extends ContentPopup {

   public static void show(String loanKey) {
      PopupPanel instance = new AddReviewPopup(loanKey);
      instance.show();
      instance.center();
   }
   
   
   private String loanKey;
   private RatingPanel rating;
   private TextArea review;
   
   public AddReviewPopup(String loanKey) {
      super(false);
      this.loanKey = loanKey;
      
      VerticalPanel panel = new VerticalPanel();
      FormPanel form = new FormPanel();
      panel.add(Headers.subheader("Add a review"));
      form.add("Rating", rating = new RatingPanel(0, true));
      form.add("Review", review = new TextArea());
      review.setSize("450px", "100px");
      panel.add(form);
      BButtonBar buttonBar = new BButtonBar();
      buttonBar.add(new BButton("Submit", BButton.PRIMARY, new AddReviewHandler()));
      buttonBar.add(new BButton("Cancel", BButton.DEFAULT, new CancelHandler()));
      panel.add(buttonBar);
      add(panel);
   }
   
   private Feedback getFeedback() {
      return new Feedback(
            "",
            Integer.valueOf(rating.getValue()),
            review.getText(),
            0,
            loanKey);
   }
   
   private class AddReviewHandler implements ClickHandler {

      @Override
      public void onClick(ClickEvent event) {
         Loader.show();
         Service.getPublicService().addFeedback(
               getFeedback(),
               "",
               "",
               new SimpleCallback<Void>() {

                  @Override
                  public void success(Void result) {
                     Loader.hide();
                     Move.get().refresh();
                     AlertBox.showSuccess("Review added");
                     if (LoansRequester.isInitialised()) LoansRequester.get().refresh();
                     AddReviewPopup.this.hide();
                  }

                  @Override
                  public void failure() {
                  }

               });
      }
      
   }
   
   private class CancelHandler implements ClickHandler {

      @Override
      public void onClick(ClickEvent event) {
         AddReviewPopup.this.hide();
      }
      
   }
   
}
